package com.example.park.controller;

import com.example.common.utils.R;
import com.example.park.entity.UserEntity;
import com.example.park.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.example.park.weixin.OpenIdUtil.oauth2GetOpenid;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Api(tags = "登录接口")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 管理员登录
     * @param map
     * @return
     */
    @ApiOperation("管理员登录")
    @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
    public R adminLogin(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        UserEntity user = userService.adminLogin(username, password);
        if (user != null) {
            return R.ok().put("list", user);
        }
        return R.error("登录失败！");
    }

    /**
     * 小程序登录
     * @param map
     * @return
     */
    @ApiOperation("小程序登录，若用户不存在自动注册，参数{\"code\":1, \"state\":\"用户类型\"}")
    @RequestMapping(value = "weiXinLogin", method = POST)
    public R weiXinLogin(@RequestBody Map<String, Object> map) {
        String state = map.get("state").toString();
        String code = map.get("code").toString();
        System.out.println(code);
        String openid = oauth2GetOpenid(code);
        UserEntity user = userService.weiXinLogin(Integer.valueOf(state), openid);
        if (user != null) {
            return R.ok("登录成功！").put("list", user);
        }
        return R.error("登录失败！");
    }
}
